import React, { Component } from 'react'
import { Switch, Route, NavLink } from 'react-router-dom'
import { Button } from 'antd';
import store from '../store'
import {CHANGEAGE} from '../store/type'
const Small1 = React.lazy(() => import('./Small1'));
const Small2 = React.lazy(() => import('./Small2'));
const Small3 = React.lazy(() => import('./Small3'));

export default class Layout extends Component {
  constructor() {
    super()
    this.state = {
      name: '',
      age: 1
    }
  }
  componentDidMount() {
    // 这是进入页面时获取并修改数据
    this.setState(store.getState());
    // 进入页面就要订阅数据
    this.unsubscribe = store.subscribe(()=>{
      console.log(111);
      // 当订阅的数据变化时，这个回调函数就会执行
      this.setState(store.getState());
    })
  }
  componentWillUnmount() {
    // 在即将离开组件时，取消订阅
    this.unsubscribe()
  }
  changeAge() {
    let actionA = {type: CHANGEAGE, age: 69}
    store.dispatch(actionA);
  }
  render() {
    return (
      <div>
        <p>我是一个大的页面，包含了一些会切换的子页面</p>
        <p>我是{this.state.name}，我今年{this.state.age}岁</p>
        <NavLink to="/layout/small1">small1</NavLink>
        <NavLink to="/layout/small2">small2</NavLink>
        <NavLink to="/layout/small3">small3</NavLink>
        <br />
        <Button type="primary">Primary Button</Button>
        <Button  onClick={()=>this.changeAge()}>修改年龄</Button>
        <Switch>
          {/* 路由组件中要写完整的路径，不能只写子路由 */}
          {/* 不要在父路由中写exact，要放在子路由中 */}
          <Route exact path="/layout/small1" component={Small1}></Route>
          <Route exact path="/layout/small2" component={Small2}></Route>
          <Route exact path="/layout/small3" component={Small3}></Route>
        </Switch>
      </div>

    )
  }
}
